//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include "FixedList.h"

FixedList::FixedList(unsigned int length)
{
    Length=length;
    head=tail=new Node;
    if (NULL == tail) {
        fprintf(stderr,"no memory for fixed list");
        exit(1);
    }
    for (currentLength = 1;currentLength < Length;currentLength++) {
        current=new Node;
        tail->next=current;
        tail=current;
    }
    currentLength=0;
    current=head;
}

FixedList::~FixedList()
{
    current=head;
    while (current != tail) {
        Node * temp=current;
        current=current->next;
        delete  temp;
    }
}

void FixedList::AddItem(unsigned int item)
{
    if (currentLength == 0) {//just fill the current node
        current=head;
        current->data=item;
        currentLength++;
    }
    else if (currentLength < Length) {
        current=current->next;
        current->data=item;
        currentLength++;
    }
    else {//all nodes has been used,so use the first node,but move it to the list tail.
        current=head;
        head=current->next;
        tail->next=current;
        tail=current;
        current->next=NULL;
        tail->data=item;
    }
}

unsigned int FixedList::GetCurrentLength()
{
    return currentLength;
}

bool FixedList::IsFull()
{
    return currentLength>=Length;
}

int FixedList::GetArray(unsigned int * array, unsigned int len)
{
    if(len < currentLength)return -1;
    Node * temp=head;
    unsigned int i=0;
    while (i < currentLength) {
        array[i]=temp->data;
        temp=temp->next;
        i++;
    }
    return 0;
}

unsigned int FixedList::GetLastItem()
{
    return current->data;
}
